#!/bin/bash
set -e

MYSQL_CONFIG="/opt/zbox/etc/mysql/my.cnf"
APACHE_CONFIG="/opt/zbox/etc/apache/httpd.conf"

if [ "${1:0:1}" == "-" ]; then
  zbox --help
elif [ "$#" == "0" ]; then
  if [ ! -d "/opt/zbox" ]; then
    tar -zxf /tmp/zbox.tar.gz -C /opt/
    if [[ "${BIND_ADDRESS}" == [fF][aA][lL][sS][eE] ]] && [ -f "${MYSQL_CONFIG}" ]; then
      #sed -Ei 's/^bind-address/#&/' ${MYSQL_CONFIG}
      sed -e 's/^bind-address.*$/bind-address            = 0.0.0.0/' -i ${MYSQL_CONFIG}
    fi
  else
    WORK_DIR=`ls /opt/zbox`
    if [ -z "${WORK_DIR}" ];then
      tar -zxf /tmp/zbox.tar.gz -C /opt/
      if [[ "${BIND_ADDRESS}" == [fF][aA][lL][sS][eE] ]] && [ -f "${MYSQL_CONFIG}" ]; then
        #sed -Ei 's/^bind-address/#&/' ${MYSQL_CONFIG}
        sed -e 's/^bind-address.*$/bind-address            = 0.0.0.0/' -i ${MYSQL_CONFIG}
      fi
    fi
  fi
  export PATH=/opt/zbox/:$PATH
  cat /opt/zbox/README && zbox start
  if [ -n "${USER}" -a -n "${PASSWD}" ]; then
    /opt/zbox/bin/htpasswd -b /opt/zbox/auth/users ${USER} ${PASSWD}
    chmod 0644 /opt/zbox/auth/users
  fi

  if [ -n "${SMTP_HOST}" ];then
    echo "${SMTP_HOST}" >> /etc/hosts
  fi
  sleep 120
  loop=1
  while [ ${loop} -eq 1 ]
  do
    wget http://localhost/ -O /dev/null || exit 1
    sleep 30
  done
else
  exec "$@"
fi
